package wht.jly.forum.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import wht.jly.forum.utils.validatecode.filter.ImageValidateCodeFilter;
import wht.jly.forum.utils.validatecode.properties.ImageValidateCodeProperties;

import javax.sql.DataSource;

/**
 * @author lanyangji
 * @date 2019/2/27 21:38
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ImageValidateCodeProperties imageValidateCodeProperties;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    private AuthenticationSuccessHandler securityAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler securityAuthenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ImageValidateCodeFilter validateCodeFilter = new ImageValidateCodeFilter(imageValidateCodeProperties, securityAuthenticationFailureHandler);
        validateCodeFilter.afterPropertiesSet();

        http
            // 将自定义的验证码过滤器加到 UsernamePasswordAuthenticationFilter 前面
            .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
            // 表单登录
            .formLogin()
                // 自定义登录页
                .loginPage("/user/login")
                // 处理登录的请求
                .loginProcessingUrl("/login")
                // 自定义认证成功处理器
                .successHandler(securityAuthenticationSuccessHandler)
                .failureHandler(securityAuthenticationFailureHandler)
                // 自定义认证失败处理器
                .and()
            // remember-me
            .rememberMe()
                // token的持久化配置
                .tokenRepository(persistentTokenRepository)
                // rememberMe的过期时间
                .tokenValiditySeconds(604800)
                // 拿到token之后用哪个UserDetailsService去登录
                .userDetailsService(customUserDetailsService)
                .and()
            // 登出
            .logout()
                // 自定义登出请求
                .logoutUrl("/logout")
                // 自定义登出成功后重定向的URL，默认是登录页
                //.logoutSuccessUrl("/user/login")
                // 登出的时候，删除COOKIE
                .invalidateHttpSession(true)
                .and()
            // 授权
            .authorizeRequests()
                .antMatchers("/logout").permitAll()
                .antMatchers("/user/login").permitAll()
                // 管理员
                .antMatchers("/admin/**").hasRole("admin")
                // 其他的请求都需要认证
                .anyRequest().authenticated()
                .and()
            // session并发控制
            .sessionManagement()
                // 同一个账号只能在一个地点登录（同一个浏览器）
                .maximumSessions(1);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        // 忽略请求
        web.ignoring()
                // 验证码
                .antMatchers( "/code/image")
                // 注册
                .antMatchers("/user/reg", "/user")
                // 静态资源
                .antMatchers("/js/*", "/css/*", "/img/*", "/webjars/**")
                // 文件上传
                .antMatchers("/file/upload");
    }

    /**
     * "记住我"的持久化配置
     *
     * JdbcTokenRepositoryImpl 会在数据库中建一个表 persistent_logins，
     * 会在其中存入用户的用户名及其token，及最近使用时间。
     *
     * 用户登录的时候，RememberMeAuthenticationFilter会根据浏览器本地的cookie,
     * 去数据库中这张表得到用户名，然后查出用户的信息，通过 userDetailsService返回
     *
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource);

        return repository;
    }

    /**
     * 注入密码加密器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
